package com.jixiang.order.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jixiang.apiFeignt.clients.GoodsClient;
import com.jixiang.model.common.dtos.ResponseResult;
import com.jixiang.model.common.enums.AppHttpCodeEnum;
import com.jixiang.model.goods.dtos.GoodsDto;
import com.jixiang.model.goods.dtos.GoodsMemberDtos;
import com.jixiang.model.goods.entity.GsGoodsSkus;
import com.jixiang.model.goods.entity.GsGoodsSkusValue;
import com.jixiang.model.order.entity.OsOrderValue;
import com.jixiang.model.user.entity.UsUser;
import com.jixiang.order.dao.OsOrderInfoDao;
import com.jixiang.model.order.entity.OsOrderInfo;
import com.jixiang.order.service.OsOrderInfoService;
import com.jixiang.order.service.OsOrderValueService;
import com.jixiang.utils.thread.UserThread;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.jixiang.common.constants.OrderConstants.*;
import static com.jixiang.common.constants.RedisConstants.*;

/**
 * (OsOrderInfo)表服务实现类
 *
 * @author makejava
 * @since 2023-11-07 12:46:22
 */
@Service("osOrderInfoService")
public class OsOrderInfoServiceImpl extends ServiceImpl<OsOrderInfoDao, OsOrderInfo> implements OsOrderInfoService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    RedissonClient redissonClient;
    @Resource
    private OsOrderValueService osOrderValueService;
    @Autowired
    GoodsClient goodsClient;
    @Override
    public ResponseResult getOrder(String id) {
//        OsOrderInfo osOrderInfo = query().eq("id", id).list().get(0);
//        Date createTime = osOrderInfo.getCreateTime();
//        long create = createTime.getTime();
//        long time = 10*60*1000;//10分钟
//        Date beforeDate = new Date(create + time);//10分钟前的时间
//
//        Date now = new Date();
//        long diff = beforeDate.getTime() - now.getTime();
//        long second = diff/1000;
//        osOrderInfo.setEndTime(second);
        OsOrderInfo osOrderInfo = getOrderById(id);
        if(osOrderInfo.getOrderState() == 0){
//            long create = osOrderInfo.getCreateTime().getTime();
//            long time = 10*60*1000;//10分钟
//            Date beforeDate = new Date(create + time);//10分钟前的时间
//
//            Date now = new Date();
//            long diff = beforeDate.getTime() - now.getTime();
//            long second = diff/1000;
            Date createTime = osOrderInfo.getCreateTime();
            long create = createTime.getTime() / 1000+600;
            Date now = new Date();
            long nowl = now.getTime()/1000;
            osOrderInfo.setEndTime(create-nowl);
        }
        return ResponseResult.okResult(osOrderInfo);
    }
    //计算两个时间相差的秒数
    public  long getTime(String startTime, String endTime) throws ParseException, ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long eTime = df.parse(endTime).getTime();
        long sTime = df.parse(startTime).getTime();
        long diff = (eTime - sTime) / 1000;
        return diff;
    }
    @Override
    public ResponseResult getOrderList(int orderState, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        UsUser user = UserThread.getUser();
        if(user == null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_EXPIRE);
        }
        if(orderState==0){
            orderState=10;
        }
        else if (orderState==1) {
            orderState=ORDER_STATE_UNPAID;
        }
        else if (orderState==2) {
            orderState=ORDER_STATE_PAYED;
        }
        else if (orderState==3 ){
            orderState=ORDER_STATE_OK;
        }else if (orderState==4 ){
            orderState=ORDER_STATE_FINAL;
        }else if (orderState==5 ){
            orderState=ORDER_STATE_FINAL;
        }
        else if (orderState==6 ){
            orderState=ORDER_STATE_EXPIRE;
        }

        List<OsOrderInfo> list = query().eq(orderState != 10, "order_state", orderState).eq("user_id", user.getId()).orderByDesc("create_time").list();
        list.forEach(item -> {
            List<OsOrderValue> orderValueList = osOrderValueService.query().eq("order_id", item.getId()).list();
            orderValueList.forEach(valueItem -> {
                GoodsDto goodsInfoById = goodsClient.getGoodsInfoById(valueItem.getGoodsId().toString());
                GoodsMemberDtos goodsMemberDtos = new GoodsMemberDtos();
                goodsMemberDtos.setName(goodsInfoById.getName());
                goodsMemberDtos.setCount(valueItem.getCount());
                goodsMemberDtos.setTotalPrice(valueItem.getGoodsTotalPrice());
                goodsMemberDtos.setPic(goodsInfoById.getMainPic());
//                List<GsGoodsSkus> skus = goodsInfoById.getSkus();
                if(goodsInfoById.getSkus()!=null){
                    List<GsGoodsSkus> collect = goodsInfoById.getSkus().stream().filter(sku -> {
                        boolean equals = sku.getId().equals(valueItem.getGoodsSkuId());
                        return equals;
                    }).collect(Collectors.toList());
                    GsGoodsSkus gsGoodsSkus = collect.get(0);
                    List<GsGoodsSkusValue> skusValues = gsGoodsSkus.getSpecs();
                    String text;
                    List<String> collect1 = skusValues.stream().map(skusValue -> {
                        return skusValue.getName() + ":" + skusValue.getValueName() ;
                    }).collect(Collectors.toList());
                    String join = String.join(",", collect1);
                    goodsMemberDtos.setText(join);
                    goodsMemberDtos.setPrice(gsGoodsSkus.getPrice());
                    valueItem.setGoodsMemberDtos(goodsMemberDtos);
                }else {
                    goodsMemberDtos.setText(goodsInfoById.getName());
                    goodsMemberDtos.setPrice(goodsInfoById.getPrice());
                    valueItem.setGoodsMemberDtos(goodsMemberDtos);
                }

            });
            Date createTime = item.getCreateTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(createTime);
            item.setCreateTimeStr(format);
            if(item.getOrderState() == 0){
                long create = createTime.getTime();
                long time = 10*60*1000;//10分钟
                Date beforeDate = new Date(create + time);//10分钟前的时间

                Date now = new Date();
                long diff = beforeDate.getTime() - now.getTime();
                long second = diff/1000;
                item.setEndTime(second);
            }
            item.setOsOrderValues(orderValueList);
        });
        PageInfo page = new PageInfo(list);
        return ResponseResult.okResult(page);
    }

    public OsOrderInfo getOrderById(String id){
        String redisData = stringRedisTemplate.opsForValue().get(REDIS_PREX_ORDER + id);
        if(StrUtil.isNotBlank(redisData)){
            OsOrderInfo bean = JSONUtil.toBean(redisData, OsOrderInfo.class);
            return bean;
        }
        if(redisData!=null){
            return null;
        }
        RLock lock = redissonClient.getLock(REDIS_LOCK_ORDER + id);
        try {
            boolean tryLock = lock.tryLock(500, TimeUnit.MILLISECONDS);
            if(!tryLock){
                getOrder(id);
            }
            OsOrderInfo osOrderInfo = query().eq("id", id).list().get(0);
            if(osOrderInfo.getOrderState() == 0){
                Date createTime = osOrderInfo.getCreateTime();
                long create = createTime.getTime();
                long time = 10*60*1000;//10分钟
                Date beforeDate = new Date(create + time);//10分钟前的时间

                Date now = new Date();
                long diff = beforeDate.getTime() - now.getTime();
                long second = diff/1000;
                osOrderInfo.setEndTime(second);
            }

            JSONObject jsonObject = JSONUtil.parseObj(osOrderInfo);
            stringRedisTemplate.opsForValue().set(REDIS_PREX_ORDER + id,jsonObject.toString(),REDIS_EXPIRE_ORDER,TimeUnit.HOURS);
            return osOrderInfo;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }


    }

}

